<?php

namespace Biz\service\brandAccount;

use Biz\cache\brand\BrandScoreCache;
use Biz\model\brand\Brand as mBrand;
use Biz\model\brandAccount\BrandAccountAuth;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\model\brandAccount\BrandAccountShop;
use Biz\model\wiki\Wiki as mWiki;
use Biz\pockets\constInterface\BrandLevel;
use Biz\service\brand\Brand;
use Biz\service\wiki\ObjRelateWiki as sObjRelateWiki;
use Doraemon\model\Photos as mPhotos;
use Doraemon\model\PicStickers as mPicStickers;
use Doraemon\service\Favorite;
use Doraemon\service\Photos as sPhotos;
use Doraemon\service\User as sUser;
use Doraemon\tools\ImgUrl;
use hhz\constant\basic\UserExtendPhoneScene;
use Doraemon\tools\Log;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\model\Phone as PhoneModel;

class BrandAccount
{
    const AUTH_LAST_DAY = 60;//临期60天，重新认证


    /**
     * 获取品牌的账户信息
     * @param $brandId
     * @return array|mixed
     */
    public static function getBrandAccountInfo($brandId)
    {
        $accountInfo = BrandAccountInfo::getOneByWhere([
            'brand_id' => $brandId,
            'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
        ]);
        $info = [];
        if ($accountInfo) {
            $authInfo = BrandAccountAuth::getOneByWhere([
                'account_id' => $accountInfo['id'],
                'auth_status' => BrandAccountAuth::AUTH_STATUS_USED
            ]);
            $info = self::formatAccount($accountInfo, $authInfo);
        }
        return $info;
    }

    public static function getBrandAccountInfoByUid($uid)
    {
        $accountInfo = BrandAccountInfo::getOneByWhere([
            'uid' => $uid,
            'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
        ]);
        $info = [];
        if ($accountInfo) {
            $authInfo = BrandAccountAuth::getOneByWhere([
                'account_id' => $accountInfo['id'],
                'auth_status' => BrandAccountAuth::AUTH_STATUS_USED
            ]);
            $info = self::formatAccount($accountInfo, $authInfo);
        }
        return $info;
    }

    /**
     * 根据账户id获取账户信息
     * @param $accountId
     * @return array|mixed
     */
    public static function getAccountInfoById($accountId)
    {
        $accountInfo = BrandAccountInfo::getOneByWhere([
            'id' => $accountId,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
        ]);
        $info = [];
        if ($accountInfo) {
            $authInfo = BrandAccountAuth::getOneByWhere([
                'account_id' => $accountInfo['id'],
                'auth_status' => BrandAccountAuth::AUTH_STATUS_USED
            ]);
            $info = self::formatAccount($accountInfo, $authInfo);
        }
        return $info;
    }

    /**
     * 根据uid获取账户列表
     * @param $uid
     * @return array|bool
     */
    public static function getAllByUid($uid)
    {
        $list = [];
        $accountlist = BrandAccountInfo::getAllByWhere([
            'uid' => $uid,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
            'ORDER' => ['id' => 'DESC'],
        ]);
        if ($accountlist) {
            $accountIds = array_column($accountlist, 'id');
            $authList = BrandAccountAuth::getAllByWhere([
                'account_id' => $accountIds,
                'auth_status' => BrandAccountAuth::AUTH_STATUS_USED
            ]);
            $authList = $authList ? array_column($authList, null, 'account_id') : [];
            foreach ($accountlist as $row) {
                $authInfo = $authList[$row['id']] ?? [];
                $list[] = self::formatAccount($row, $authInfo);
            }
        }
        return $list;
    }

    public static function getAllByUids($uids)
    {
        $list = [];
        $accountlist = BrandAccountInfo::getAllByWhere([
            'uid' => $uids,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
            'ORDER' => ['id' => 'DESC'],
        ]);
        if ($accountlist) {
            $accountIds = array_column($accountlist, 'id');
            $authList = BrandAccountAuth::getAllByWhere([
                'account_id' => $accountIds,
                'auth_status' => BrandAccountAuth::AUTH_STATUS_USED
            ]);
            $authList = $authList ? array_column($authList, null, 'account_id') : [];
            foreach ($accountlist as $row) {
                $authInfo = $authList[$row['id']] ?? [];
                $list[] = self::formatAccount($row, $authInfo);
            }
        }
        return $list;
    }

    private static function formatAccount($info, $authInfo)
    {
        $info['certification_time'] = $authInfo['auth_start_time'] ?? '';
        $info['type_des'] = BrandAccountInfo::ACCOUNT_TYPE[$info['type']];
        $info['status_des'] = BrandAccountInfo::ACCOUNT_STATUS_MAP[$info['account_status']];
        $info['letter_time'] = ($authInfo && strtotime($authInfo['letter_time']) > 0) ? $authInfo['letter_time'] : '';
        $info['letter_status'] = ($authInfo && date('Ymd', strtotime($authInfo['letter_time'])) >= date('Ymd')) ? 1 : 0;
        $info['letter_expired'] = $info['letter_status'] ? $info['descrip'] : '认证已到期，新一轮认证资料还在路上';
        return $info;
    }

    public static function getShopInfos($accountId)
    {
        $shopInfos = BrandAccountShop::getAllByWhere(['account_id' => $accountId, 'shop_status' => BrandAccountShop::SHOP_STATUS_VALID]);
        return $shopInfos;
    }

    /**
     * 获取商铺的wiki数量
     * @param $accountId
     * @return array
     */
    public static function getAccountShopWikiCount($accountId)
    {
        $shopList = self::getShopInfos($accountId);
        $where = [];
        foreach ($shopList as $key => $row) {
            if ($row['shop_id'] && in_array($row['type'], BrandAccountShop::SHOP_TYPE_WIKI)) {
                $where['OR #more']['AND #' . ($key + 1)] = [
                    'channel_type' => $row['type'],
                    'channel_shop_id' => $row['shop_id'],
                ];
            }
        }
        $count = $where ? mWiki::count($where) : 0;
        return $count;
    }

    /**
     * 根据品牌id获取主店铺
     * @param $brand_id
     * @return array
     */
    public static function getIsMainShopByBrandId($brand_id): array
    {
        $id = BrandAccountInfo::getOneByWhere([
            'brand_id' => $brand_id,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED
        ], 'id');
        if (!$id) {
            return [];
        }

        $data = BrandAccountShop::getOneByWhere([
            'is_main_shop' => BrandAccountInfo::IS_MAIN_SHOP_SHOW,
            'shop_status' => BrandAccountShop::SHOP_STATUS_VALID,
            'account_id' => $id
        ], ['url', 'type', 'name', 'shop_id']);
        return $data ?: [];
    }

    /**
     * 获取用户认证信息
     * @param $uid
     */
    public static function getUserAuthInfo($uid)
    {
        $info = [];
        $accountList = BrandAccountInfo::getAllByWhere([
            'uid' => $uid,
            'account_status[!]' => BrandAccountInfo::ACCOUNT_STATUS_DEL,
            'ORDER' => ['id' => 'DESC']
        ]);
        if ($accountList) {
            $accountList = array_column($accountList, null, 'type');
            $accountInfo = [];
//            foreach ($accountList as $type => $row) {
//                if (empty($accountInfo)) {
//                    switch ($type) {
//                        case BrandAccountInfo::ACCOUNT_TYPE_BRAND:
//                            if ($row['account_status'] == BrandAccountInfo::ACCOUNT_STATUS_USED) {
//                                $accountInfo = $row;
//                            }
//                            break;
//                        case BrandAccountInfo::ACCOUNT_TYPE_SHOP:
//                            if ($row['account_status'] == BrandAccountInfo::ACCOUNT_STATUS_USED) {
//                                $accountInfo = $row;
//                            }
//                            break;
//                    }
//                } else {
//                    break;
//                }
//            }
            $accountList = array_values($accountList);
            $accountInfo = $accountInfo ? $accountInfo : $accountList[0];
            $brandId = $accountInfo['brand_id'];
            $brandInfo = $brandId ? Brand::getBrandsInfoByIds($brandId) : [];
            $brandInfo = $brandInfo ? $brandInfo[$brandId] : [];
            $shopList = [];
            $canAuth = 0;
            $authId = 0;
            $authInfo = BrandAccountAuth::getOneByWhere(['account_id' => $accountInfo['id'], 'auth_status[!]' => BrandAccountAuth::AUTH_STATUS_DEL, 'ORDER' => ['id' => 'DESC']]);
            if (self::isBeforeExpire($accountInfo) && $authInfo['auth_status'] == BrandAccountAuth::AUTH_STATUS_USED) {//临期重新认证
                $canAuth = 1;
            } else if ($authInfo['auth_status'] == BrandAccountAuth::AUTH_STATUS_NOPASS) {
                $authId = $authInfo['id'];
                $canAuth = 1;
            }
            if ($authInfo['auth_status'] != BrandAccountAuth::AUTH_STATUS_USED) {
                $shopList = $authInfo['shop'] ? json_decode($authInfo['shop'], true) : [];
                $shopList = array_map(function ($_data) {
                    return BrandAccountShop::_filter($_data);
                }, $shopList);
            } else {
                $shopList = BrandAccountShop::getAllByWhere(['account_id' => $accountInfo['id'], 'shop_status' => BrandAccountShop::SHOP_STATUS_VALID]);
            }
            $phone = $authInfo['phone_encrypt_id'] ? PhoneModel::getExtendPhone($authInfo['phone_encrypt_id'], UserExtendPhoneScene::BRAND_AUTH_INFO_PHONE) : '';
            $info = [
                'id' => $authId,//认证id
                'account_id' => $accountInfo['id'],
                'type' => $accountInfo['type'],
                'uid' => $accountInfo['uid'],
                'nick' => $authInfo['nick'],
                'brand_id' => $accountInfo['brand_id'],
                'company' => $authInfo['company'] ?? '',
                'credit_code' => $authInfo['credit_code'] ?? '',
                'name' => $authInfo['name'] ?? '',
                'phone' => $phone,
                'email' => $authInfo['email'] ?? '',
                'weixin' => $authInfo['weixin'] ?? '',
                'license' => ($authInfo && $authInfo['license']) ? self::handleResImgUrl($authInfo['license']) : [],
                'license_time' => $authInfo['license_time'] ?? '',
                'letter' => ($authInfo && $authInfo['letter']) ? self::handleResImgUrl($authInfo['letter']) : [],
                'letter_time' => $authInfo['letter_time'] ?? '',
                'certificate' => ($authInfo && $authInfo['certificate']) ? self::handleResImgUrl($authInfo['certificate']) : [],
                'authorization' => ($authInfo && $authInfo['authorization']) ? self::handleResImgUrl($authInfo['authorization']) : [],
                'application' => ($authInfo && $authInfo['application']) ? self::handleResImgUrl($authInfo['application']) : [],
                'shop_type' => BrandAccountShop::SHOP_TYPE,
                'shop' => $shopList,
                'account_status' => $accountInfo['account_status'],
                'auth_status' => $authInfo ? $authInfo['auth_status'] : BrandAccountAuth::AUTH_STATUS_DEFAULT,//认证状态(0:待审核1:审核通过2:审核不通过3:使用中4:认证过期9:删除)
                'reason' => $authInfo['reason'] ?? '',
                'can_auth' => $canAuth,//是否可以认证 1:可以 0:不可以
                'pack_type' => $brandInfo ? $brandInfo['pack_type'] : 0,
            ];
        }
        return $info;
    }

    /**
     *获取用户的收藏数量
     */
    public static function getIdea($uid)
    {
        $data = Favorite::getFavoriteListForIdeaBook($uid, 1, 0, 1000);
        $response = [];

        if (!empty($data)) {
            $pic_ids = array_values($data);
            //格式化点图标签
            $stickers = mPicStickers::getStickersByNoteId($pic_ids);
            $stickersMap = empty($stickers) ? [] : array_column($stickers, 'img_tags', 'pic_id');
            $imgTag = array_map(function ($v) {
                return sObjRelateWiki::admFormatImgTags($v);
            }, $stickersMap);

            //图片关联商品
            $relateInfo = sObjRelateWiki::admNoteRelateList($pic_ids);

            foreach ($pic_ids as $pic_id) {
                $photoInfo = mPhotos::getPhoto($pic_id);
                if ($photoInfo) {
                    $picList = sPhotos::getImageList($photoInfo['pic_list']);
                    //组装数据
                    $response[$pic_id] = array_map(function ($v) use ($relateInfo, $imgTag) {
                        $tempRelateList = isset($relateInfo[$v['pic_id']]) ? $relateInfo[$v['pic_id']]['list'] : [];
                        $tempRelateList = empty($tempRelateList) ? [] : array_column($tempRelateList, 'id');
                        $v['wiki'] = implode(',', $tempRelateList);
                        $v['imgTag'] = isset($imgTag[$v['pic_id']]) ? $imgTag[$v['pic_id']] : "";
                        return $v;
                    }, $picList);
                }
            }
        }
        return $response;
    }

    /**
     * 获取审核列表
     * @param $params
     * @return array
     */
    public static function admGetAccountList($params = [])
    {
        $params['account_status[!]'] = BrandAccountInfo::ACCOUNT_STATUS_DEL;
        $accountList = BrandAccountInfo::getAllByWhere($params);
        if (!empty($accountList)) {
            $brandIds = array_column($accountList, 'brand_id');
            $uids = array_column($accountList, 'uid');
            $brandInfos = [];
            if ($params['type'] == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                $brandInfos = mBrand::getInfoByIds($brandIds);
                $brandInfos = array_column($brandInfos, null, 'id');
            }
            //获取用户头像
            $users = sUser::getBatchBasicUserInfo($uids);
            if ($users) {
                $users = array_column($users, 'small_avatar', 'uid');
            }

            foreach ($accountList as $_k => $_v) {
                $_v['small_avatar'] = '';
                if (isset($users[$_v['uid']])) {
                    $_v['small_avatar'] = $users[$_v['uid']];
                }
                if ($params['type'] == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                    $_v['pack_type'] = ($brandInfos && isset($brandInfos[$_v['brand_id']])) ? $brandInfos[$_v['brand_id']]['pack_type'] : 0;
                    $_v['brand_name'] = ($brandInfos && isset($brandInfos[$_v['brand_id']])) ? $brandInfos[$_v['brand_id']]['brand_name'] : '';
                    $_v['level'] = BrandLevel::BRAND_LEVELS[$brandInfos[$_v['brand_id']]['level']];
                    $_v['growth_value'] = $brandInfos[$_v['brand_id']]['growth_value'];
                    $brandScore = BrandScoreCache::getBrandScore($_v['brand_id']);
                    $brandScore = $brandScore ?: 0;
                    $_v['brand_score'] = $brandScore;
                    $_v['logo'] = ($brandInfos && isset($brandInfos[$_v['brand_id']])) ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brandInfos[$_v['brand_id']]['logo'],
                        ImgUrl::IMAGE_SIZE_SQ_PHONE) : '';
                }
                $data[$_k] = $_v;
            }
        }

        $result = [];
        $result['list'] = $data;
        unset($params['ORDER'], $params['LIMIT']);
        $result['total'] = !empty($accountList) ? BrandAccountInfo::count($params) : 0;
        return $result;
    }

    public static function admGetAccountInfo($accountId, $authId = 0)
    {
        $account = BrandAccountInfo::getOneByWhere(['id' => $accountId]);
        if (!$authId) {
            $authInfo = BrandAccountAuth::getOneByWhere(['account_id' => $accountId, 'auth_status' => BrandAccountAuth::AUTH_STATUS_USED]);
            $shopList = BrandAccountShop::getAllByWhere(['account_id' => $accountId, 'shop_status' => BrandAccountShop::SHOP_STATUS_VALID]);
            if ($account && empty($authInfo)) {
                $authInfo = BrandAccountAuth::getOneByWhere([
                    'account_id' => $accountId,
                    'auth_status[!]' => BrandAccountAuth::AUTH_STATUS_DEL,
                    'ORDER' => ['id' => 'DESC']
                ]);
            }
        } else {
            $authInfo = BrandAccountAuth::getOneByWhere(['id' => $authId, 'account_id' => $accountId]);
            if ($authInfo['auth_status'] != BrandAccountAuth::AUTH_STATUS_USED) {
                $shopList = ($authInfo && $authInfo['shop']) ? json_decode($authInfo['shop'], true) : [];
                if (is_array($shopList)) {
                    $shopList = array_map(function ($_data) {
                        return BrandAccountShop::_filter($_data);
                    }, $shopList);
                }
            } else {
                $shopList = BrandAccountShop::getAllByWhere(['account_id' => $accountId, 'shop_status' => BrandAccountShop::SHOP_STATUS_VALID]);
            }
        }
        if ($account) {
            $account['in_start_time'] = (strtotime($account['in_start_time']) > 0) ? $account['in_start_time'] : '';
            $account['in_end_time'] = (strtotime($account['in_end_time']) > 0) ? $account['in_end_time'] : '';

            $brandInfo = mBrand::getBrandInfoById($account['brand_id']);
            $account['level'] = BrandLevel::BRAND_LEVELS[$brandInfo['level']];
            $account['growth_value'] = $brandInfo['growth_value'];
            $brandScore = BrandScoreCache::getBrandScore($account['brand_id']);
            $brandScore = $brandScore ?: 0;
            $account['brand_score'] = $brandScore;
        }
        if ($authInfo) {
            $authInfo['phone'] = $authInfo['phone_encrypt_id'] ? PhoneModel::getExtendPhone($authInfo['phone_encrypt_id'], UserExtendPhoneScene::BRAND_AUTH_INFO_PHONE) : '';
        }
        $info = [
            'account' => $account,
            'auth' => $authInfo,
            'shop' => $shopList
        ];
        return $info;
    }

    public static function admGetAuthList($params)
    {
        $params['auth_status[!]'] = BrandAccountAuth::AUTH_STATUS_DEL;
        $authList = BrandAccountAuth::getAllByWhere($params);
        if ($authList) {
            $accountIds = array_column($authList, 'account_id');
            $accountList = BrandAccountInfo::getAllByWhere(['account_status[!]' => BrandAccountInfo::ACCOUNT_STATUS_DEL, 'id' => $accountIds]);
            $uids = array_column($accountList, 'uid');
            $brandIds = array_column($accountList, 'brand_id');
            $accountList = array_column($accountList, null, 'id');
            $brandInfos = mBrand::getBrandListByIds($brandIds);
            $users = sUser::getBatchBasicUserInfo($uids);
            $users = $users ? array_column($users, 'small_avatar', 'uid') : [];

            $data = [];
            foreach ($authList as $row) {
                $accountInfo = $row['account_id'] ? $accountList[$row['account_id']] : [];
                $brandId = $accountInfo['brand_id'] ?? 0;
                $uid = $accountInfo['uid'] ?? 0;
                $brandInfo = $brandId ? $brandInfos[$brandId] : [];
                $row['uid'] = $uid;
                $row['brand_id'] = $brandId;
                $row['brand_name'] = $brandInfo['brand_name'] ?? '';
                $row['pack_type'] = $brandInfo['pack_type'] ?? 0;
                $row['brand_type'] = $accountInfo['brand_type'] ?? 0;
                $row['in_end_time'] = ($accountInfo && strtotime($accountInfo['in_end_time']) > 0) ? $accountInfo['in_end_time'] : '';
                $row['account_status'] = $accountInfo['account_status'] ?? 0;
                $row['small_avatar'] = $users[$uid] ?? '';
                $row['logo'] = ($brandInfo && isset($brandInfo['logo'])) ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brandInfo['logo'],
                    ImgUrl::IMAGE_SIZE_SQ_PHONE) : '';
                $data[] = $row;
            }
            $result['list'] = $data;
            unset($params['ORDER'], $params['LIMIT']);
            $result['total'] = !empty($accountList) ? BrandAccountAuth::count($params) : 0;
        } else {
            $result = ['list' => [], 'total' => 0];
        }
        return $result;
    }


    private static function handleResImgUrl($data): array
    {
        $res = [];
        if (strpos($data, ',') !== false) {
            $data = explode(',', $data);
            if ($data) {
                foreach ($data as $val) {
                    if (strpos($val, 'http') != false) {
                        $img['ori_pic_id'] = static::parseImgUrl($val);
                        $img['ori_o_phbig_url'] = $val;
                    } else {
                        $img['ori_pic_id'] = $val;
                        $img['ori_o_phbig_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $val, ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                    }
                    $res[] = $img;
                }
            }
        } else {
            if (strpos($data, 'http') != false) {
                $img['ori_pic_id'] = static::parseImgUrl($data);
                $img['ori_o_phbig_url'] = $data;
            } else {
                $img['ori_pic_id'] = $data;
                $img['ori_o_phbig_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $data, ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            }
            $res[] = $img;
        }
        return $res;
    }

    private static function parseImgUrl($url)
    {
        $newUrl = parse_url($url);
        $path = $newUrl['path'];
        $arr = explode('/', $path);
        return array_pop($arr);
    }

    /**
     * 是否即将到期
     * @param $accountInfo
     * @return bool
     */
    public static function isBeforeExpire($accountInfo)
    {
        if ($accountInfo) {
            $today = date('Y-m-d');
            if ($today >= $accountInfo['in_start_time'] && $today <= $accountInfo['in_end_time']) {
                //临期开始日期
                $beforeStartDay = strtotime($accountInfo['in_end_time']) - (86400 * self::AUTH_LAST_DAY);
                $beforeStartDay = date('Y-m-d', $beforeStartDay);
                return $today >= $beforeStartDay;
            }
        }
        return false;
    }

}
